<template>
  <div class="select-housing">
    <a-row :wrap="false">
      <a-col class="left">
        <VillageTree
          :companyId="branchId"
          :showCompany="true"
          :refreshParams="refreshParams"
          :refreshTrigger="refreshTrigger"
          @getCurrent="getCurrentSelect"
          @request="$utils.commonRequest"
        />
      </a-col>
      <a-col flex="1" class="right">
        <div v-if="noVillage" class="no_village">
          <a-empty :image="simpleImage" />
        </div>
        <CustomTable
          v-show="!noVillage"
          ref="customTableRef"
          :columns="columns"
          :loadDataAtInit="false"
          :hasPagination="true"
          :requestInfo="{
            service: '/village', // 请求服务
            serviceUrl: '/houseResource/resourceList', // 请求url
            serviceType: 'get', // 请求方式
          }"
          :extraParams="{
            ...searchData,
            with_sub_room: 1,
          }"
          :tableHeight="600"
          :excludeImport="true"
          :tableConfig="$store.getters.tableConfig"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
          @getListResult="getListResult"
          tableId="housingInformation"
          @request="$utils.commonRequest"
        >
          <template #leftTitle>
            <a-input-search
              style="width: 200px"
              v-model:value="keywordsValue"
              placeholder="查询房号"
              @search="onSearch"
              allowClear
            />
          </template>
          <template #column-room_alias_id="{ record }">
            {{ record.room_alias_id || "--" }}
          </template>
          <template #column-owner_name="{ record }">
            <div v-if="record?.owner_list && record?.owner_list.length">
              <span>
                {{ record.owner_list.map((item) => item.name).join(",") }}</span
              >
            </div>
            <div v-else>--</div>
          </template>
        </CustomTable>
      </a-col>
      <a-col
        :span="6"
        class="right"
        v-if="informationList && informationList.length > 0"
      >
        <div class="apartment beauty-scroller-bar">
          <div class="apartment-box">
            <div
              class="apartment-item"
              v-for="(item, index) in informationList"
              :key="index"
            >
              <div class="apartment-row">
                <div class="apartment-row-name">编号：</div>
                <div class="apartment-row-text">
                  {{ item.room_alias_id || "--" }}
                </div>
              </div>
              <div class="apartment-row">
                <div class="apartment-row-name">名称：</div>
                <div class="apartment-row-text">{{ item.room_name }}</div>
              </div>
              <div class="apartment-row">
                <div class="apartment-row-name" style="line-height: 24px">
                  经营状态：
                </div>
                <div class="apartment-row-text">
                  <a-tag>{{ item.room_status_txt }}</a-tag>
                </div>
              </div>
              <div class="apartment-row">
                <div class="apartment-row-name">当前租户：</div>
                <div
                  class="apartment-row-text"
                  v-if="item?.owner_list && item?.owner_list.length"
                >
                  <span>
                    {{
                      item.owner_list.map((item) => item.name).join(",")
                    }}</span
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
    <div class="drawer-footer">
      <a-button class="mr-10" @click="closeModal">取消</a-button>
      <a-button type="primary" @click="onSubmit">保存</a-button>
    </div>
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  toRefs,
  computed,
  watch,
  reactive,
  onMounted,
  nextTick,
} from "vue";
import { CustomTable , VillageTree} from "bl-common-vue3";
import request from "@/common/utils/request";
import { useRoute } from "vue-router";
import { Form, message, Modal, Empty } from "ant-design-vue";

export default defineComponent({
  name: "SelectHousing",
  components: { VillageTree, CustomTable },
  props: {},
  setup() {
    const route = useRoute();

    const state = reactive({
      count: 0,
      refreshTrigger: 0,
      columns: [
        {
          title: "编号",
          dataIndex: "room_alias_id",
          key: "room_alias_id",
          width: 100,
        },
        {
          title: "名称",
          dataIndex: "room_name",
          key: "room_name",
          width: 100,
        },
        {
          title: "经营状态",
          dataIndex: "room_status_txt",
          key: "room_status_txt",
          width: 100,
        },
        {
          title: "建筑面积",
          dataIndex: "build_area",
          key: "build_area",
          width: 100,
        },
        {
          title: "当前租户",
          dataIndex: "owner_name",
          key: "owner_name",
          width: 100,
        },
      ],
      informationList: [],
      selectedRowKeys: [],
      searchData: {},
      selectData: {},
      keywordsValue: "",
      branchId: 0,
      refreshParams: {},
      noVillage: false,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
    });

    // tab表格实例
    const customTableRef = ref(null);

    const getCurrentSelect = (info) => {
      console.log(info.current, "getCurrentSelect");
      state.noVillage = false;
      //   项目
      if (info.current.childType == "village") {
        state.searchData = {
          village_id: info.current.id,
        };
      }
      //   楼宇
      if (info.current.childType == "build") {
        state.searchData = {
          village_id: info.current.village_id,
          build_id: info.current.id,
        };
      }
      //   楼层
      if (info.current.childType == "layer") {
        state.searchData = {
          village_id: info.current.extra.village_id,
          build_id: info.current.extra.build_id,
          layer_id: info.current.id,
        };
      }
      //   房间
      if (info.current.childType == "room") {
        state.searchData = {
          village_id: info.current.extra.village_id,
          build_id: info.current.extra.build_id,
          layer_id: info.current.extra.layer_id,
          room_id: info.current.id,
        };
      }
      
      // 公司
      if (info.current.childType == "department") {
        let villageIds = info.current.villageList
          .map((item) => item.id)
          .join(",");
        state.searchData = {
          village_id: villageIds,
        };
      }

      // 没有项目时
      if (info.current.noVillage == 1) {
        state.noVillage = true;
        return;
      }

      state.selectData = info.current;

      customTableRef.value.loadData(true);
    };

    const onSearch = (value) => {
      state.searchData["keywords"] = value;
      customTableRef.value.loadData(true);
    };

    const onSelectChange = (selectedRowKeys, selectedRows) => {
      console.log("selectedRowKeys changed: ", selectedRowKeys, selectedRows);
      state.informationList = selectedRows;
      state.selectedRowKeys = selectedRowKeys;
    };

    const getListResult = ({ list }) => {
      state.informationList = [];
      setTimeout(() => {
        list.forEach((item) => {
          state.selectedRowKeys.forEach((selectKey) => {
            if (item.id == selectKey) {
              state.informationList.push(item);
            }
          });
        });
      }, 10);
    };

    const closeModal = () => {
      if (window?.microApp?.getData()?.isMainDrawer) {
        window?.microApp?.getData()?.closeModal();
      } else {
        context.emit("onClose");
      }
    };

    const onSubmit = () => {
      if (window?.microApp?.getData()?.isMainDrawer) {
        if (state.informationList.length) {
          window?.microApp
            ?.getData()
            ?.success(state.informationList, state.selectData);
          window?.microApp?.getData()?.closeModal();
        } else {
          message.warn("请至少选择一个房间");
        }
      } else {
        context.emit("onClose");
      }
    };

    onMounted(() => {
      nextTick(() => {
        state.selectedRowKeys =
          route.query.ids.split(",").map((item) => Number(item)) || [];
        if (route.query.branchId) {
          state.branchId = Number(route.query.branchId);
        }

        let villageData = window?.microApp?.getData()?.villageData;
        if (villageData.childType == "village") {
          state.searchData = {
            village_id: villageData.id,
          };
          state.refreshParams = {
            selected: {
              villageId: villageData.village_id,
            },
          };
        }
        //   楼宇
        if (villageData.childType == "build") {
          state.searchData = {
            village_id: villageData.village_id,
            build_id: villageData.id,
          };
          state.refreshParams = {
            selected: {
              villageId: villageData.village_id,
              buildId: villageData.id,
            },
          };
        }
        //   楼层
        if (villageData.childType == "layer") {
          state.searchData = {
            village_id: villageData.extra.village_id,
            build_id: villageData.extra.build_id,
            layer_id: villageData.id,
          };
          state.refreshParams = {
            selected: {
              villageId: villageData.extra.village_id,
              buildId: villageData.extra.build_id,
              layerId: villageData.id,
            },
          };
        }
        //   房间
        if (villageData.childType == "room") {
          state.searchData = {
            village_id: villageData.extra.village_id,
            build_id: villageData.extra.build_id,
            layer_id: villageData.extra.layer_id,
            room_id: villageData.id,
          };
          state.refreshParams = {
            selected: {
              villageId: villageData.extra.village_id,
              buildId: villageData.extra.build_id,
              layerId: villageData.extra.layer_id,
              roomId: villageData.id,
            },
          };
        }
      });
    });

    return {
      ...toRefs(state),
      closeModal,
      getCurrentSelect,
      onSelectChange,
      customTableRef,
      onSearch,
      onSubmit,
      getListResult,
    };
  },
});
</script>

<style lang="less" scoped>
.select-housing {
  width: 100%;
  height: 100%;
  background: #fff;

  .left {
    min-width: 200px;
    height: 600px;
    margin-left: 5px;
    margin-right: 10px;
    border: 1px solid #f1f1f1;
  }
  .right {
    .apartment {
      width: 100%;
      padding-left: 10px;
      padding-right: 10px;
      height: 600px;
      overflow-y: auto;

      .apartment-box {
        border: 1px solid rgb(211, 211, 211);
        font-size: 12px;

        .apartment-item {
          border-bottom: 1px solid rgb(211, 211, 211);

          &:last-child {
            border-bottom: none;
          }

          .apartment-row {
            display: flex;
            align-items: center;
            line-height: 1.3;
            padding: 0px 6px;
            padding-top: 8px;

            &:last-child {
              padding-bottom: 8px;
            }

            .apartment-row-name {
              width: 70px;
              color: #999;
              text-align: right;
            }

            .apartment-row-text {
              flex: 1;
              color: #353535;
            }
          }
        }
      }
    }
    .no_village {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    :deep(.ant-table-pagination-right) {
      padding-right: 15px;
    }
  }
}
</style>
